package cn.ad.service;

import cn.ad.entity.AdSpace;
import cn.ad.enumration.AdFormat;
import cn.ad.enumration.MaterialFormat;
import cn.ad.exception.AdSpaceValidateException;
import cn.ad.handler.SqlSessionHandler;
import cn.ad.interceptor.PageParameter;
import cn.ad.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdSpaceService {

	@Autowired
	private SqlSessionHandler sqlSessionHandler;

	/**
	 * 跟据查询条件查询广告位列表
	 */
	public DataTableModel findAdSpaces(Map<String, Object> searchMap, PageParameter pageInfo, int searchStatus) {
		searchMap.put("searchStatus", searchStatus);
		List<AdSpaceModel> adSpaceList = sqlSessionHandler.selectList("adSpaceMapper.adSpace:list:page", searchMap, pageInfo);
		return new DataTableModel(pageInfo.getTotalCount(), adSpaceList);
	}

	/**
	 * 根据策略ID查询出策略关联的广告位列表
	 */
	public List<AdSpaceModel> findAdSpaceByStrategyId(int sid) {
		return sqlSessionHandler.selectList("adSpaceMapper.selectByStrategyId", sid);
	}

	public AdSpaceInfoModel findAdSpaceInfoById(int adId) {
		AdSpaceInfoModel adSpace=sqlSessionHandler.selectOne("adSpaceMapper.adSpaceInfo",adId);
		return adSpace;
	}

	public Integer findAdSpaceTemplateId(int id) {
		return sqlSessionHandler.selectOne("adSpaceMapper.selectTemplateId",id);
	}

	public void updateAdSpaceStatus(int id,int status) {
		Map<String,Object> map=new HashMap<>();
		map.put("id",id);
		map.put("status",status);
		sqlSessionHandler.update("adSpaceMapper.updateStatus",map);
	}
	/**
	 *保存广告位
	 *需要更新模版元素表的format_type
	 *
	 */
	@Transactional
	public void saveSapce(AdSpace adSpace, boolean isInsert) {
		if(isRepeat(adSpace)){
			throw new AdSpaceValidateException(AdSpaceValidateException.ErrorCode.ADSPACE_NAME_REPEAT);
		}

		if(adSpace.getFormatId()==AdFormat.ADFORMAT_NATIVE.getValue()){
			//如果是原生广告的话，更新对应的模板元素表的format_type
			//将图片格式转成文本value
			StringBuilder sb = new StringBuilder();
			if(!StringUtils.isEmpty(adSpace.getMaterialFormat())){
				String[] types = (adSpace.getMaterialFormat().toLowerCase()).split(",");
				for(String str:types){
					sb.append(MaterialFormat.forValue(str)).append(",");
				}
				if(sb.length()>0){
					sb.deleteCharAt(sb.length()-1);
				}
			}
			Map map = new HashMap<>(2);
			map.put("templateId", adSpace.getTemplateId());
			map.put("formatType", sb.toString());
			sqlSessionHandler.update("adTemplateSpecMapper.update:formatType", map);
		}
		if(isInsert){
			sqlSessionHandler.insert("adSpaceMapper.insert", adSpace);
		}else{
			sqlSessionHandler.insert("adSpaceMapper.update", adSpace);
		}

	}

	/**
	 * 删除广告位,需要检查广告位是否产生投放数据
	 * @param id
	 */
	public void deleteSapce(int id) {

		sqlSessionHandler.update("adSpaceMapper.deleteById",id);
	}

	public ResultSetList<AdRptModel> getSpaceRptList(Map<String, Object> searchMap, PageParameter parameter) {
		List<AdRptModel> list=sqlSessionHandler.selectList("adSpaceMapper.adspace:list:for:report",searchMap);
		ResultSetList<AdRptModel> result=new ResultSetList<>(list.size(),list);
		return result;
	}

	/***
	 * 查询供应商下的广告位列表
	 */
	public List<AdSpace> getAdSpaceListForSupplier(Integer supplierId) {
		return sqlSessionHandler.selectList("adSpaceMapper.adspace:list:for:supplier", supplierId);
	}

	/**
	 * 验证是否存在重复命名
	 * @param adSpace
	 * @return
	 */
	private boolean isRepeat(AdSpace adSpace){
		int count = sqlSessionHandler.selectOne("adSpaceMapper.adSpace:checkname",adSpace);
		return count>0;
	}

	/**
	 * 根据id 查询单个广告位信息
	 * @param id
	 * @return
	 */
	public AdSpace read(int id){
		return sqlSessionHandler.selectOne("adSpaceMapper.selectById",id);
	}

	/**
	 * 根据媒体集合查询供应商下媒体的ID list
	 * @param ids
	 * @return
	 */
	public List<Integer> selectAdSpaceIds(List<Integer> ids) {
		Map<String,Object> params = new HashMap<>();
		params.put("status",1);
		params.put("ids",ids);
		return sqlSessionHandler.selectList("adSpaceMapper.select:adspaceIds", params);
	}
}
